package net.wicp.tams.plugin.task.kubernetes;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;

import com.alibaba.fastjson.JSONObject;

import io.fabric8.kubernetes.api.model.ReplicationController;
import net.wicp.tams.common.apiext.yaml.YamlUtil;
import net.wicp.tams.common.exception.ProjectException;
import net.wicp.tams.common.others.kubernetes.KubeClient;
import net.wicp.tams.plugin.TaskAssit;

@Mojo(name = "addrc", requiresProject = true, threadSafe = false)
public class AddRc extends AbstractMojo {

	@Parameter(defaultValue = "${project.basedir}/k8s/rc.yml", property = "rc", required = true)
	private File rc;

	/**
	 * apiserver的url
	 */
	@Parameter(property = "url", required = false)
	private String url;

	@Parameter(defaultValue = "default", property = "namespace", required = false)
	private String namespace;
	// 回调地址
	@Parameter(property = "callback", required = false)
	private String callback;
	// 回调的会话id
	@Parameter(property = "msgid", required = false)
	private String msgid;

	@Override
	public void execute() throws MojoExecutionException, MojoFailureException {
		TaskAssit.initMasterUrl(url);
		try {
			JSONObject json = YamlUtil.readYaml(new FileInputStream(rc));
			String rcName = json.getJSONObject("metadata").getString("name");
			ReplicationController rcQuery = KubeClient.getRC(namespace, rcName);
			if (rcQuery != null) {
				boolean delret = KubeClient.delRc(namespace, rcName);
				if (!delret) {
					throw new MojoFailureException("删除原有的rc出错");
				}
			}
			KubeClient.createRc(namespace, new FileInputStream(rc));
			TaskAssit.sendMsg(getLog(), callback, msgid,true);
		} catch (FileNotFoundException | ProjectException e) {
			throw new MojoFailureException("创建rc出错", e);
		}
	}

}
